package liangtWorkSpace.simple;

/**
 * @ClassName SearchInsert
 * @Description : 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * 你可以假设数组中无重复元素
 * @Author : LiangT
 * @Date : 2020/6/18 18:41
 */
public class SearchInsert {
    public static int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length < 1){
            return 0;
        }
        int[] ints =  new int[nums.length+1];
        for (int i =0; i < nums.length;i++){
            ints[i] = nums[i];
            if (target > nums[i]){
                continue;
            }
            if (target == nums[i]){
                return i;
            }
            if (target < nums[i]){
                for (int j = nums.length-1;j > i ;j--){
                    ints[j+1] = nums[j];
                }
                return i;
            }
        }
        ints[nums.length] = target;
        nums = ints;
        return nums.length-1;
    }

    public static int searchInsert1(int[] nums, int target) {
        if (nums == null || nums.length < 1){
            return 0;
        }
        for (int i =0; i < nums.length;i++){
            if (target <= nums[i]){
                return i;
            }
        }
        return nums.length;
    }

    public static int searchInsert2(int[] nums, int target) {
        if (nums == null || nums.length < 1){
            return 0;
        }
        int heigh = nums.length-1;
        int weight = 0;
        while (weight < heigh){
            int time = (heigh-weight)/2+weight;
            if (nums[time] > target){
                heigh = time-1;
            }
            if (nums[time] < target){
                weight = time+1;
            }
            if (nums[time] == target){
                return time;
            }
        }
        return weight;
    }

    public static void main(String[] args) {
        int[] ints = new int[]{1,3,5,6};
        System.out.println(searchInsert2(ints,7));
    }
}
